package com.immunology.service;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.encoding.ShaPasswordEncoder;

import com.immunology.domain.Complaint;
import com.immunology.domain.ComplaintType;
import com.immunology.domain.Role;
import com.immunology.domain.Syndrome;
import com.immunology.domain.User;

public class DBInitializer implements InitializingBean{

	@Autowired
	private RoleService roleService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SyndromeService syndromeService;
	
	@Autowired
	private ComplaintTypeService complaintTypeService;
	
	@Autowired
	private ComplaintService complaintService;
	
	@Override
	public void afterPropertiesSet() throws Exception {
		initializeRole();
	}
	
	private void initializeRole() {
		List<Role> roles = roleService.getAll();
		if (roles.isEmpty()) {
			roleService.save(new Role("ROLE_ADMIN"));
			roleService.save(new Role("ROLE_USER"));
			roleService.save(new Role("ROLE_DOCTOR"));
			roleService.save(new Role("ROLE_ANONYMOUS"));
			
			Syndrome syndrome = new Syndrome();
			syndrome.setName("Allergic");
			
			ComplaintType complaintType = new ComplaintType();
			complaintType.setName("Nose");
			complaintType.setMultyplier(1.0);
			complaintType.setSyndrome(syndrome);
			
			Complaint complaint = new Complaint();
			complaint.setComplaintType(complaintType);
			complaint.setName("Sneeze");
			
			syndromeService.save(syndrome);
			complaintTypeService.save(complaintType);
			complaintService.save(complaint);
			User user = new User();
			user.setFirstName("admin");
			user.setMiddleName("admin");
			user.setLastName("admin");
			user.setLogin("admin");
			user.setPassword(new ShaPasswordEncoder(256).encodePassword("admin", user.getLogin()));
			
			roles.clear();
			roles.add(roleService.getAll().get(0));
			user.setRoles(roles);
//			user.setRole(new Role("ROLE_ADMIN"));
			user.setPost("admin");
			
			userService.save(user);
		}
	}

}
